﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Smile.Mvvm.Service
{
    public class ServiceLocator
    {
        // @Properties
        public static ServiceLocator Instance
        {
            get
            {
                if (_instance == null)
                {
                    lock (_syncRoot)
                    {
                        if (_instance == null)
                        {
                            _instance = new ServiceLocator();
                        }
                    }
                }
                return _instance;
            }
        }

        // @Public
        public static void Register<T>(T service)
        {
            if (Instance._container.ContainsKey(typeof(T)))
            {
                Instance._container[typeof(T)] = service;
            }
            else
            {
                Instance._container.Add(typeof(T), service);
            }
        }

        public static void Delete<T>()
        {
            if (Instance._container.ContainsKey(typeof(T)))
            {
                Instance._container.Remove(typeof(T));
            }
        }

        public static T Retrieve<T>()
        {
            object retrieved;
            if (Instance._container.TryGetValue(typeof(T), out retrieved))
            {
                return (T)retrieved;
            }
            throw new ArgumentException("Unable to find " + typeof(T).FullName + " service type");
        }

        // @Private
        private static volatile ServiceLocator  _instance;
        private static object                   _syncRoot = new object();
        private Dictionary<Type, object>        _container = new Dictionary<Type, object>();

        private ServiceLocator()
        {
        }
    }
}
